package ua.org.nuos.sdms.middle.dao;

import org.apache.commons.lang.Validate;
import ua.org.nuos.sdms.middle.entity.EmailVerification;
import ua.org.nuos.sdms.middle.util.validator.EmailVerificationValidator;

import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: dio
 * Date: 8/24/12
 * Time: 2:57 PM
 * To change this template use File | Settings | File Templates.
 */
@Local
@Stateless
public class EmailVerificationDaoBean {

    private static Logger logger = Logger.getLogger(EmailVerificationDaoBean.class.getSimpleName());

    @PersistenceContext(unitName = "persistence")
    protected EntityManager em;

    private EmailVerificationValidator validator;

    @PostConstruct
    protected void init() {
        validator = new EmailVerificationValidator(em);
    }

    /**
     * Create email verification
     *
     * @param emailVerification EmailVerification
     *                         EmailVerification.user is required
     *                         EmailVerification.code is required
     */
    public void create(EmailVerification emailVerification) {
        validator.validate(emailVerification);
        em.persist(emailVerification);
    }

    /**
     * Find email verification
     *
     * @param userId
     * @return
     */
    public EmailVerification find(long userId) {
        Validate.isTrue(userId > 0);

        try {
            return em.createNamedQuery(EmailVerification.QUERY_FIND_BY_USER_ID, EmailVerification.class)
                    .setParameter("id", userId).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    /**
     * Find email verification
     *
     * @param code
     * @return
     */
    public EmailVerification find(String code) {
        Validate.notEmpty(code);

        try {
            return em.createNamedQuery(EmailVerification.QUERY_FIND_BY_CODE, EmailVerification.class)
                    .setParameter("code", code).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    /**
     * Remove email verification
     *
     * @param userId
     */
    public void remove(long userId) {
        Validate.isTrue(userId > 0);

        EmailVerification registration = find(userId);
        if (registration != null) {
            em.remove(registration);
        }
    }
}
